package com.fudan.backend.service.impl;

import com.fudan.backend.dao.AccountDao;
import com.fudan.backend.dao.ActivityDao;
import com.fudan.backend.exception.BaseException;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Account;
import com.fudan.backend.pojo.Activity;
import com.fudan.backend.pojo.statics.AccountStatic;
import com.fudan.backend.pojo.statics.ActivityStatus;
import com.fudan.backend.pojo.statics.BillType;
import com.fudan.backend.service.AccountService;
import com.fudan.backend.service.ActivityService;
import com.fudan.backend.util.Snowflake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    ActivityDao activityDao;

    @Autowired
    Snowflake snowflake;

    @Autowired
    AccountDao accountDao;

    @Autowired
    AccountService accountService;

    @Override
    @Transactional
    public RetCode addActivity(Activity activity) {

        Double fund = activity.getFund();
        Account account = accountDao.selectAccountByAccountId(AccountStatic.WEBSHOP_ACCOUNT_ID);
        Double balance = account.getBalance();
        if(balance < fund){
            return RetCode.WEB_SHOP_ACCOUNT_BALANCE_INSUFFICIENT;
        }

        accountService.transfer(AccountStatic.WEBSHOP_ACCOUNT_ID,
                AccountStatic.INTERMEDIATE_ACCOUNT_ID, fund, BillType.COMMISSION,"活动资金转账");

        activity.setBalance(activity.getFund());
        activity.setActivityId((snowflake.nextId()).toString());
        activity.setStatus(ActivityStatus.OPEN);
        int i = activityDao.insertActivity(activity);
        if (i == 1){
            return RetCode.ACTIVITY_SUCCESS;
        }else {
            return RetCode.ACTIVITY_INSERT_FAILURE;
        }
    }

    @Override
    public PageInfo<Activity> getAllActivity(int current, int pageSize) {
        PageHelper.startPage(current, pageSize);
        List<Activity> activities = activityDao.selectAllActivity();
        return new PageInfo<Activity>(activities, 5);
    }

    @Override
    public PageInfo<Activity> getAllOngoingActivity(int current, int pageSize) {
        PageHelper.startPage(current, pageSize);
        List<Activity> activities = activityDao.selectAllOngoingActivity();
        return new PageInfo<Activity>(activities, 5);
    }

    @Override
    public Activity getActivityByActivityId(String activityId) {
        Activity activity = activityDao.selectActivityByActivityId(activityId);
        if(activity == null){
            throw new BaseException(RetCode.ACTIVITY_NOT_FOUND);
        }
        return activity;
    }
}
